(function($) {
    $.fn.mention_only = function(options) {
        var dis = this;
        var settings = $.extend({
            json : ""
            }, options);
        // $(this).autosize({append: "\n"});
		addHtmlChars(dis);
        $(this).autosize({append: "\n"});
        
        searchElement(dis,settings.json);

        //append styles and html elements for list

        
    }
}(jQuery));

function searchElement(dis,data){
    
    var value_toSearch = ""; // value on the textbox or textarea
    var ret = ""; // return search suggestion
    var countIndexSearch = 0; // count of total search(this is for keydown and keyup)
    var totalIndexSearch = 0; // total search
    var array_search = new Array();
    var size  = "";
    

    $(dis).on({
        "keydown" :function(event){
            var value = $(this).val();
            totalIndexSearch = $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").find(".mentionList").length;
            if(event.which==40){
                if(countIndexSearch<totalIndexSearch){
                    countIndexSearch++;
                }else{
                    countIndexSearch = 0;
                }
                event.preventDefault();
            }else if(event.which==38){
                if(countIndexSearch>0){
                    countIndexSearch--;
                }else{
                    countIndexSearch = totalIndexSearch;
                }
                event.preventDefault();
            }else if(event.which==13){
                if(totalIndexSearch>0){
                    var activeEle = $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").find(".mentionActive");
                    console.log(activeEle.text())
                    $(dis).before("<div class='mentionSelected' data-id="+ activeEle.attr("data-id") +"><i class='removeTagg_i icon-remove-sign' style='margin-right: 5px;cursor: pointer;'></i>"+$.trim(activeEle.text())+"</div>");
                    $(dis).val("");
                    countIndexSearch = 0;                                        
                }                
                event.preventDefault();
            }else if(event.which==8){
                if($(dis).val()==""){
                    
                    if($(".activeRemove").length==1){
                        $(".activeRemove").remove()
                    }else{
                        $(dis).prev().addClass("activeRemove")
                    }
                    event.preventDefault();
                }
            }
            $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").children(".mentionList").removeClass("mentionActive")
            $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").children(".mentionList").eq(countIndexSearch).addClass("mentionActive")
            size  = value.length+1;
            newwidth =  size*11;          // rough guesstimate of width of char
            if(newwidth<= $(dis).parent().width()){
                $(dis).css({width:newwidth});     // apply new width
            }
        },  
        "keyup" : function(event){
                ret = ""
                var ctrToAppend = 0;
                var value = $(this).val();
                if(event.which!=40 && event.which!=38){
                    $(".mentionSelected").each(function(){
                        array_search.push($.trim($(this).text()));
                    })

                    value = value.split(" ");
                    for(var j in value){
                        // value_toSearch = $.trim(value[j].substr(1,value[j].length).toLowerCase());
                        value_toSearch = $.trim(value[j].toLowerCase());
                        if(value_toSearch){
                            // if(value[j] && value[j].charAt(0)=="@"){

                                for(var i in data){
                                    if(data[i]['name'].toLowerCase().search(value_toSearch) !== -1){
                                        if(array_search.indexOf(data[i]['name'])==-1){
                                            ret += '<div class="mentionList" data-id="'+ data[i]['id'] +'" style=""><i class="icon-caret-right"> </i><span class="mentionList_txt">'+ $.trim(data[i]['name']) +'</span></div>';
                                            ctrToAppend++;
                                            if(ctrToAppend==10){
                                                break;
                                            }
                                        }
                                    }
                                }
                                var margin_searchChoice = $(dis).closest(".mentionContainer_only").find(".mentionSelectedContainer").height()+9;
                                $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").html(ret).css("margin-top",margin_searchChoice)
                                $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").html(ret)
                                $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").children(".mentionList").eq(0).addClass("mentionActive")
            
                            // }else{
                            //     //console.log("hindi @ ung simula")
                            //     $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").html("")
                            //     countIndexSearch = 0;
                            // }
                        }else{
                            //console.log("Di Pwede walang laman")
                            $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").html("")
                            countIndexSearch = 0;
                        }
                    }
                    array_search = [];
                }
                var val = $(this).val();
                size  = val.length+1;
                newwidth =  size*11;          // rough guesstimate of width of char
                // alert()+"<="+$(dis).parent().width())
                if($(dis).width()<= $(dis).parent().width()){

                    $(dis).css({width:newwidth});     // apply new width
                }
        },
        "focusout" : function(){
            // $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").html("")
        },
    })
    $("body").on("mouseenter",".mentionContainer_only .mentionList",function(){
        $(".mentionList").removeClass("mentionActive");
        $(this).addClass("mentionActive");
        countIndexSearch = $(this).index();
    })
    $("body").on("click",".mentionContainer_only .mentionList",function(){
        var activeEle = $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").find(".mentionActive");
        if(activeEle.text()){
            console.log(activeEle.text())
            $(dis).before("<div class='mentionSelected' data-id="+ activeEle.attr("data-id") +"><i class='removeTagg_i icon-remove-sign' style='margin-right: 5px;cursor: pointer;'></i>"+$.trim(activeEle.text())+"</div>");
            $(dis).val("");
            $(dis).closest(".mentionContainer_only").find(".mentionSearchChoice").html("")
            $(dis).focus();
            countIndexSearch = 0;
        }
    })
    $("body").on("click",".mentionContainer_only .removeTagg_i",function(){
        $(this).closest(".mentionSelected").remove();
    })
    $("body").on("click",".mentionSelectedContainer",function(){
        $(dis).focus();
    })
}
function getJSONFromFile (path,callback){
    $.getJSON(path,function(data){
        callback(data)
    });
}
function addHtmlChars(dis){
    $(dis).wrap('<div class="mentionContainer_only" style="width: 100%;"></div>');
    $(dis).wrap('<div class="mentionSelectedContainer"></div>');
    $(dis).closest(".mentionContainer_only").append('<div class="mentionSearchChoice"></div>');
}